import axios from 'axios'

export default {
  namespaced: true,
  
  state: {
    token: localStorage.getItem('token') || null,
    user: null,
    loading: false,
    error: null
  },
  
  getters: {
    isAuthenticated: state => !!state.token,
    user: state => state.user,
    loading: state => state.loading,
    error: state => state.error
  },
  
  mutations: {
    AUTH_START(state) {
      state.loading = true
      state.error = null
    },
    AUTH_SUCCESS(state, { token, user }) {
      state.token = token
      state.user = user
      state.loading = false
      state.error = null
    },
    AUTH_ERROR(state, error) {
      state.loading = false
      state.error = error
    },
    SET_USER(state, user) {
      state.user = user
    },
    CLEAR_AUTH(state) {
      state.token = null
      state.user = null
    }
  },
  
  actions: {
    // 注册
    async register({ commit }, userData) {
      try {
        commit('AUTH_START')
        const response = await axios.post('/auth/register', userData)
        const { token, user } = response.data
        
        // 保存token到本地存储
        localStorage.setItem('token', token)
        
        commit('AUTH_SUCCESS', { token, user })
        return user
      } catch (error) {
        commit('AUTH_ERROR', error.response?.data?.message || '注册失败')
        throw error
      }
    },
    
    // 登录
    async login({ commit }, credentials) {
      try {
        commit('AUTH_START')
        const response = await axios.post('/auth/login', credentials)
        const { token, user } = response.data
        
        // 保存token到本地存储
        localStorage.setItem('token', token)
        
        commit('AUTH_SUCCESS', { token, user })
        return user
      } catch (error) {
        commit('AUTH_ERROR', error.response?.data?.message || '登录失败')
        throw error
      }
    },
    
    // 加载用户信息
    async loadUser({ commit, state }) {
      if (!state.token) return
      
      try {
        commit('AUTH_START')
        const response = await axios.get('/auth/me')
        commit('SET_USER', response.data)
        return response.data
      } catch (error) {
        commit('AUTH_ERROR', error.response?.data?.message || '加载用户信息失败')
        // 如果token无效，清除本地存储
        if (error.response?.status === 401) {
          localStorage.removeItem('token')
          commit('CLEAR_AUTH')
        }
        throw error
      }
    },
    
    // 登出
    logout({ commit }) {
      localStorage.removeItem('token')
      commit('CLEAR_AUTH')
    }
  }
} 